package com.dai.rpc.loadbanlance.loadbanlancer;

import com.dai.rpc.factory.SingletonFactory;
import com.dai.rpc.loadbanlance.AbstractLoadBalance;
import com.dai.rpc.message.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

/**
 * 随机挑选一个实例
 */
@Slf4j
public class RandomLoadBalance extends AbstractLoadBalance {

    @Override
    protected String doSelect(List<String> serviceUrlList, RpcRequest rpcRequest) {
        Random random = SingletonFactory.getInstance(Random.class);
        return serviceUrlList.get(random.nextInt(serviceUrlList.size()));
    }


    @Override
    protected InetSocketAddress doLoadBalance(Set<String> services) {

        int size = services.size();
        Random random = SingletonFactory.getInstance(Random.class);
        // 随机从可用服务列表中选取服务
        Optional<String> first = services.stream().skip(random.nextInt(size)).findFirst();
        if(first.isPresent()){
            String ipPort = first.get();
            String[] split = ipPort.split(",");
            log.info("客户端走了缓存...");
            log.info("使用随机负载均衡策略...");
            InetSocketAddress inetAddress = new InetSocketAddress(split[0], Integer.parseInt(split[1]));
            return inetAddress;
        }
        return null;

    }

    @Override
    public String name() {
        return "random";
    }
}
